package com.qqtech.qquan.mall.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qqtech.core.common.annotation.VisitAnnt;
import com.qqtech.core.common.enums.RespEnum;
import com.qqtech.core.common.util.StringUtil;
import com.qqtech.core.common.util.TimeUtil;
import com.qqtech.core.frame.model.PageKit;
import com.qqtech.core.frame.model.PageOrder;
import com.qqtech.core.frame.model.Result;
import com.qqtech.core.frame.service.BaseService;
import com.qqtech.qquan.mall.enums.MallConst;
import com.qqtech.qquan.mall.enums.MallShopTypeDictEnum;
import com.qqtech.qquan.mall.model.MallCart;
import com.qqtech.qquan.mall.model.MallCartQuery;
import com.qqtech.qquan.mall.model.MallCartVo;
import com.qqtech.qquan.mall.model.MallProductSpecVo;
import com.qqtech.qquan.mall.model.MallShop;
import com.qqtech.qquan.mall.service.MallCartService;
import com.qqtech.qquan.mall.service.MallProductService;
import com.qqtech.qquan.mall.service.MallProductSpecService;
import com.qqtech.qquan.mall.service.MallShopService;
import com.qqtech.qquan.mall.service.MallSupplierService;
import com.qqtech.web.context.BaseWebController;

@Controller
@RequestMapping(value = "/mall/cart")
public class MallCartController extends BaseWebController<MallCart, MallCartQuery> {
	@Resource
	private MallCartService mallCartService;
	@Resource
	private MallProductService mallProductService;
	@Resource
	private MallProductSpecService mallProductSpecService;
	@Resource
	private MallSupplierService mallSupplierService;
	@Resource
	private MallShopService mallShopService;
    
	@Override
	protected BaseService<MallCart> getBaseService() {
		return mallCartService;
	}
	
	/**
	 * 商城-购物车列表页
	 * @param mallProductQuery
	 * @return
	 */
	@VisitAnnt(type=RespEnum.LOGIN)
	@RequestMapping(value = "/index")
	@ResponseBody
	public Result index(@RequestBody MallCartQuery mallCartQuery) {
		Result result = new Result();
		//列表
		mallCartQuery.setShopId(1);//商城
		mallCartQuery.setCreatorId(super.getUserId());
		Pageable pageKit = new PageKit(new PageOrder(Direction.DESC, "mc.newAt"));
		Page<MallCartVo> page = mallCartService.queryPageBySupplier(mallCartQuery, pageKit);
		List<MallCartVo> list = page.getContent();
		//索引index
		int index = 0;
		if(mallCartQuery.getPage() != null && mallCartQuery.getPage() > 1){
			index = (mallCartQuery.getPage()-1) * 10;
		}
		
		LinkedHashMap<String, List<MallCartVo>> externaMap =  new LinkedHashMap<String, List<MallCartVo>>();
		
		if(list != null && list.size() > 0){
			for(MallCartVo mallCartVo : list){
				if(mallCartVo != null){
					//购物车库存不足处理
					if(mallCartVo.getStock() > 0){
						if(mallCartVo.getQuantity() > mallCartVo.getStock()){
							mallCartVo.setQuantity(mallCartVo.getStock());
							mallCartService.updateById(mallCartVo);
						}
					}else{
						mallCartVo.setQuantity(0);
						mallCartService.deleteById(mallCartVo.getId());
					}
					mallCartVo.setName(mallCartVo.getName());
					mallCartVo.setSpec(mallCartVo.getColor() + mallCartVo.getSpecName());
					mallCartVo.setPrice(mallCartVo.getPrice());
					mallCartVo.setMarketPrice(mallCartVo.getMarketPrice());
					if(StringUtil.isNotBlank(mallCartVo.getImg())){
						String imgStr = mallCartVo.getImg();
						if(imgStr.indexOf(";") > -1){
							String [] imgs = imgStr.split(";");
							mallCartVo.setImg(mallCartVo.getImgHandleDomain() + imgs[0] + MallConst.IMG_SMALL);
						}else{
							mallCartVo.setImg(mallCartVo.getImgHandleDomain() + mallCartVo.getImg() + MallConst.IMG_SMALL);
						}
					}
					mallCartVo.setIndex(index);
					index++;
					
					if(mallCartVo.getSupplierType() == 1){ //外地供应商
						if(externaMap.containsKey(mallCartVo.getSupplierId().toString())){
							List<MallCartVo> productList = externaMap.get(mallCartVo.getSupplierId().toString());
							productList.add(mallCartVo);
						}else{
							List<MallCartVo> newproductList = new ArrayList<MallCartVo>();
							newproductList.add(mallCartVo);
							externaMap.put(mallCartVo.getSupplierId().toString(), newproductList);
						}
					}else{
						//删除购物车 本地供应商商品（旧版本数据）
						mallCartService.deleteById(mallCartVo.getId());
					}
				}
			}
		}
		
		BigDecimal cartTotalPrice = mallCartService.getTotalPrice(super.getUserId(), 1);
		String externalDeliverTime = mallCartService.getDeliverTime(MallConst.PARAMKEY_MALL_EXTERNAL_DELIVER_TIME);
		
		result.put("cartTotalPrice", cartTotalPrice);
		result.put("externalDeliverTime", externalDeliverTime);
		result.put("externaMap", externaMap);
		result.put("externaMapKeys", externaMap.keySet());
		return result;
	}
	
	/**
	 * 圈商-购物车列表页
	 * @param mallProductQuery
	 * @return
	 */
	@VisitAnnt(type=RespEnum.LOGIN)
	@RequestMapping(value = "/indexByShop")
	@ResponseBody
	public Result indexByShop(@RequestBody MallCartQuery mallCartQuery) {
		Result result = new Result();
		if (mallCartQuery.getShopId() == null) {
			result.addErr("店铺信息错误");
			return result;
		}
		//列表
		mallCartQuery.setCreatorId(super.getUserId());
		Pageable pageKit = new PageKit(new PageOrder(Direction.DESC, "mc.newAt"));
		Page<MallCartVo> page = mallCartService.queryPageByShop(mallCartQuery, pageKit);
		List<MallCartVo> list = page.getContent();
		//索引index
		int index = 0;
		if(mallCartQuery.getPage() != null && mallCartQuery.getPage() > 1){
			index = (mallCartQuery.getPage()-1) * 10;
		}
			
		if(list != null && list.size() > 0){
			for(MallCartVo mallCartVo : list){
				if(mallCartVo != null){
					//购物车库存不足处理
					if(mallCartVo.getStock() > 0){
						if(mallCartVo.getQuantity() > mallCartVo.getStock()){
							mallCartVo.setQuantity(mallCartVo.getStock());
							mallCartService.updateById(mallCartVo);
						}
					}else{
						mallCartVo.setQuantity(0);
						mallCartService.deleteById(mallCartVo.getId());
					}
					mallCartVo.setName(mallCartVo.getName());
					mallCartVo.setSpec(mallCartVo.getColor() + mallCartVo.getSpecName());
					mallCartVo.setPrice(mallCartVo.getPrice());
					mallCartVo.setMarketPrice(mallCartVo.getMarketPrice());
					if(StringUtil.isNotBlank(mallCartVo.getImg())){
						String imgStr = mallCartVo.getImg();
						if(imgStr.indexOf(";") > -1){
							String [] imgs = imgStr.split(";");
							mallCartVo.setImg(mallCartVo.getImgHandleDomain() + imgs[0] + MallConst.IMG_SMALL);
						}else{
							mallCartVo.setImg(mallCartVo.getImgHandleDomain() + mallCartVo.getImg() + MallConst.IMG_SMALL);
						}
					}
					mallCartVo.setIndex(index);
					index++;
				}
			}
		}
		
		BigDecimal cartTotalPrice = mallCartService.getTotalPrice(super.getUserId(), mallCartQuery.getShopId());
		
		result.put("cartTotalPrice", cartTotalPrice);
		result.put("list", list);
		return result;
	}
	
	/**
	 * 添加到购物车
	 * 
	 * @param MallCartQuery
	 * @return
	 */
	@VisitAnnt(type=RespEnum.LOGIN)
	@RequestMapping(value = "/doAdd")
	@ResponseBody
	public Result doAdd(@RequestBody MallCart mallCart) {
		Result ret = new Result();
		MallProductSpecVo spec = new MallProductSpecVo();
		if (mallCart == null || mallCart.getProductId() == null
				|| mallCart.getShopId() == null) {
			ret.addErr("参数错误");
			return ret;
		}
		MallShop ms = mallShopService.getById(mallCart.getShopId());
		if(ms == null){
			ret.addErr("店铺不存在");
			return ret;
		}
		if(mallCart.getProductSpecId() == null && ms.getType().intValue() == MallShopTypeDictEnum.QQMALLSHOP.getCode()){//圈商
			List<MallProductSpecVo> specList = mallProductSpecService.queryListByProductId(mallCart.getProductId());
			if(specList != null && specList.size() == 1){
				spec = specList.get(0);
				mallCart.setProductSpecId(spec.getId());
			}else{
				ret.put("moreSpect", specList.size());
				return ret;
			}
		}else{
			spec = mallProductSpecService.getById(mallCart.getProductSpecId());
		}

		Integer stock = 0;
		if(spec != null && spec.getStock() != null && spec.getStock().intValue() > 0){
			stock = spec.getStock();
		}else{
			ret.addErr("库存不足");
			return ret;
		}
		MallCart query = new MallCart();
		query.setProductId(mallCart.getProductId());
		query.setProductSpecId(mallCart.getProductSpecId());
		query.setCreatorId(super.getUserId());
		MallCart cart = mallCartService.getOne(query);
		if(cart != null){
			cart.setQuantity(cart.getQuantity()+mallCart.getQuantity());
			if(cart.getQuantity().intValue() > stock){
				ret.addErr("库存不足");
				return ret;
			}
			cart.setUpdAt(TimeUtil.now());
			mallCartService.updateById(cart);
		}else{
			mallCart.setCreatorId(super.getUserId());
			mallCartService.handleAddProduct2Cart(mallCart);
		}
		int cartTotalProduct = mallCartService.getTotalQuantity(super.getUserId(), mallCart.getShopId());
		ret.put("cartTotalProduct", cartTotalProduct);
		//购物车商品价格合计
		/*BigDecimal cartTotalPrice = mallCartService.getTotalPrice(super.getUserId(), 1);
		ret.put("cartTotalPrice", cartTotalPrice);*/
		return ret;
	}

	/**
	 * 删除
	 * 
	 * @param MallCartQuery
	 * @return
	 */
	@VisitAnnt(type=RespEnum.LOGIN)
	@RequestMapping(value = "/doDelete")
	@ResponseBody
	public Result doDelete(@RequestBody MallCartQuery mallCartQuery) {
		Result ret = new Result();
		mallCartQuery.setCreatorId(super.getUserId());
		MallCart tmp = mallCartService.getById(mallCartQuery.getId());
		if(tmp == null){
			ret.addErr("购物车相关信息不存在");
			return ret;
		}
		if(tmp.getCreatorId().intValue() != super.getUserId().intValue()){
			ret.addErr("无权限删除购物车");
			return ret;
		}
		mallCartService.delete(mallCartQuery);
		
		return ret;
	}
	
	/**
	 * 结算
	 * 
	 * @param MallCartQuery
	 * @return
	 */
	@VisitAnnt(type=RespEnum.LOGIN)
	@RequestMapping(value = "/checkout")
	@ResponseBody
	public Result checkout(@RequestBody MallCartQuery mallCartQuery) {
		Result ret = new Result();
		
		return ret;
	}
	
	 /**
     * 购物车内某店铺商品总数量
     *
     * @param mallCartQuery
     * @return
     */
    @RequestMapping(value = "/totalQuantity")
    @ResponseBody
    public Result mallCartCount(@RequestBody MallCartQuery mallCartQuery) {
    	Result ret = new Result();
    	Integer userId = super.getUserId();
        int totalQuantity = mallCartService.getTotalQuantity(userId, mallCartQuery.getShopId());
        ret.put("totalQuantity", totalQuantity);
        BigDecimal totalPrice = mallCartService.getTotalPrice(userId, mallCartQuery.getShopId());
        ret.put("totalPrice", totalPrice);
        return ret;
    }
    
    /**
	 *更新购物车数量
	 * 
	 * @param cartList
	 * @return
	 */
	@VisitAnnt(type=RespEnum.LOGIN)
	@RequestMapping(value = "/doUpdateQuantity")
	@ResponseBody
	public Result doUpdateQuantity(@RequestBody List<MallCart> cartList) {
		Result ret = new Result();
		if(cartList != null && cartList.size() > 0){
			for(MallCart mallCart : cartList){
				if (mallCart.getId() != null && mallCart.getProductId() != null
						&& mallCart.getQuantity() != null) {
					MallCart updateCart = new MallCart();
					updateCart.setId(mallCart.getId());
					updateCart.setCreatorId(super.getUserId());
					updateCart.setProductId(mallCart.getProductId());
					updateCart.setQuantity(mallCart.getQuantity());
					//mallCartService.updateById(updateCart);   
				}
				
			}
		}
		return ret;
	}
	
	 /**
		 *更新购物车单个商品数量
		 * 
		 * @param mallCart
		 * @return
		 */
	@VisitAnnt(type=RespEnum.LOGIN)
	@RequestMapping(value = "/doUpdate")
	@ResponseBody
	public Result doUpdate(@RequestBody MallCart mallCart) {
		Result ret = new Result();
		if (mallCart.getId() != null && mallCart.getProductId() != null
				&& mallCart.getQuantity() != null) {
			MallCartQuery mallCartQuery = new MallCartQuery();
			mallCartQuery.setId(mallCart.getId());
			mallCartQuery.setCreatorId(super.getUserId());
			MallCart cart = mallCartService.getOne(mallCartQuery);
			if(cart != null){
				MallProductSpecVo spec = mallProductSpecService.getById(cart.getProductSpecId());
				if(mallCart.getQuantity() > spec.getStock()){
					ret.put("error", "库存不足");
					ret.put("stock", spec.getStock());
				}else{
					MallCart updateCart = new MallCart();
					updateCart.setId(cart.getId());
					updateCart.setQuantity(mallCart.getQuantity());
					mallCartService.updateById(updateCart);  
				}
				
			} 
		}
		return ret;
	}
}
